var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
// var session = require('express-session');
var jwt = require('express-jwt');
var {secretKey,unless,algorithms} = require('./utils/token');
require('./db');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var studentsRouter = require('./routes/students');
var classesRouter = require('./routes/classes');
var filmsRouter = require('./routes/films');
var hotsRouter = require('./routes/hots');
var soonsRouter = require('./routes/soons');
var productsRouter = require('./routes/products');
var totalsRouter = require('./routes/totals');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// app.use(session({
//   secret:"lovo",
//   resave:false, // 强制保存session，默认为true，即使它没有变化，建议false
//   saveUninitialized:true // 强制将未初始化的session存储（当新建一个sesison，但未设定属性和值时处于未初始化状态）
// }));
// app.use(jwt({secret:secretKey,algorithms}).unless(unless));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/students',studentsRouter);
app.use('/classes',classesRouter);
app.use('/films', filmsRouter);
app.use('/soons',soonsRouter);
app.use('/hots',hotsRouter);
app.use('/products',productsRouter);
app.use('/totals',totalsRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  console.log('error handle',err.status)
  if(err.status == 401){
    res.status(401);
    res.send({});
  }else{
    // render the error page
    res.status(err.status || 500);
    res.render('error');
  }
  
});

module.exports = app;
